export default function dealWithBalanceGQCMiddleware(optionsBuilder) {
	return async (resolve, source, args, context, info) => {
		let options = optionsBuilder;
		if (typeof optionsBuilder === 'function') {
			options = await optionsBuilder(source, args, context);
		}

		const {
			uid,
			ops,
			beforeCalc = ({ ops }) => ops,
			server: {
				methods: { ensureBalance, calcBalance },
			},
		} = options;

		return (ops.every(x => x.value > 0) // 全是增加操作就不检查余额
			? Promise.resolve()
			: ensureBalance({ uid, ops })
		)
			.then(() => resolve(source, args, context, info))
			.then(response => {
				beforeCalc({ uid, ops, response });
				return calcBalance({ uid, ops }).then(() => response);
			});
	};
}
